<template>
  <div class="main">
    <h3>绑定系统账户</h3>
    <a-form-model class="loginForm" ref="form" :model="model" :rules="validatorRules">
      <a-form-model-item required prop="username" label="账号">
        <a-input v-model="model.username" size="large" placeholder="请输入账号"></a-input>
      </a-form-model-item>
      <a-form-model-item required prop="password" label="密码">
        <a-input v-model="model.password" size="large" type="password" autocomplete="false" placeholder="请输入密码"></a-input>
      </a-form-model-item>

      <a-form-item style="margin-top:24px">
        <a-button
          size="large"
          type="primary"
          htmlType="submit"
          class="login-button"
          :loading="loginBtn"
          @click.stop.prevent="handleSubmit"
          :disabled="loginBtn">绑定并登录</a-button>
      </a-form-item>
      <a-form-item style="margin-top:24px">
        <a-button
          size="large"
          type="primary"
          ghost
          htmlType="submit"
          class="login-button"
          @click.stop.prevent="handleCancel">取消</a-button>
      </a-form-item>
    </a-form-model>
  </div>
</template>

<script>
import Vue from 'vue'
import { ACCESS_TOKEN, ENCRYPTED_STRING } from '@/store/mutation-types'
import { timeFix } from '@/utils/util'
import { mapActions } from 'vuex'

export default {
  components: {
  },
  data() {
    return {
      loginBtn: false,
      model: {
        username: '',
        password: '',
        openid: '',
        access_token: ''
      },
      validatorRules: {
        username: [
          { required: true, message: '请输入用户名!' },
          { validator: this.handleUsernameOrEmail }
        ],
        password: [{
          required: true, message: '请输入密码!', validator: 'click'
        }]
      }
    }
  },
  created() {
    Vue.ls.remove(ACCESS_TOKEN)
    this.model.openid = this.$route.query.openid
    this.model.access_token = this.$route.query.access_token
  },
  methods: {
    ...mapActions(['bindWxLogin']),
    handleUsernameOrEmail (rule, value, callback) {
      const regex = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/
      if (regex.test(value)) {
        this.loginType = 0
      } else {
        this.loginType = 1
      }
      callback()
    },
    // 绑定并登录
    handleSubmit() {
      this.loginBtn = true
      this.validateFields([ 'username', 'password' ], (err) => {
        if (!err) {
          let loginParams = {
            username: this.model.username,
            password: this.model.password,
            openid: this.model.openid,
            access_token: this.model.access_token
          }
          this.bindWxLogin(loginParams).then((res) => {
            this.loginSuccess()
          }).catch((err) => {
            this.requestFailed(err)
          })
        } else {
          this.validateFail()
        }
      })
    },
    // 取消绑定
    handleCancel() {
      this.$router.push({ path: '/user/login' }).catch(() => {

      })
    },
    // 校验失败
    validateFail() {
      this.loginBtn = false
    },
    validateFields(arr, callback) {
      let promiseArray = []
      for (let item of arr) {
        let p = new Promise((resolve, reject) => {
          this.$refs['form'].validateField(item, (err) => {
            if (!err) {
              resolve()
            } else {
              reject(err)
            }
          })
        })
        promiseArray.push(p)
      }
      Promise.all(promiseArray).then(() => {
        callback()
      }).catch(err => {
        callback(err)
      })
    },
    // 登录成功
    loginSuccess() {
      this.$router.push({ path: '/dashboard/analysis' }).catch(() => {
        console.log('登录跳转首页出错,这个错误从哪里来的')
      })
      this.$notification.success({
        message: '绑定成功',
        description: `${timeFix()}，欢迎回来`
      })
    },
    // 登录后台失败
    requestFailed(err) {
      let description = ((err.response || {}).data || {}).message || err.message || '请求出现错误，请稍后再试'
      this.$notification['error']({
        message: '登录失败',
        description: description,
        duration: 4
      })
      /* // 账户密码登录错误后更新验证码
      if (this.customActiveKey === 'tab1' && description.indexOf('密码错误') > 0) {
        this.$refs.alogin.handleChangeCheckCode()
      } */
      this.loginBtn = false
    }

  }
}
</script>
<style lang="less" scoped>
.main {
  h3 {
    margin-top: 36px;
    margin-bottom: 20px;
    font-size: 30px;
    font-weight: 600;
    color: #127442;
    text-align: center;
  }
  .loginForm {
    padding: 0;
    .login-button {
      padding: 0 15px;
      font-size: 16px;
      height: 40px;
      width: 380px;
    }
  }
}
.user-layout-login {
  label {
    font-size: 14px;
  }
  .getCaptcha {
    display: block;
    width: 100%;
    height: 40px;
  }

  .forge-password {
    font-size: 14px;
  }

  button.login-button {
    padding: 0 15px;
    font-size: 16px;
    height: 40px;
    width: 380px;
    margin: 0 45px 0 35px;
  }

  .user-login-other {
    text-align: left;
    margin-top: 24px;
    line-height: 22px;

    .item-icon {
      font-size: 24px;
      color: rgba(0, 0, 0, 0.2);
      margin-left: 16px;
      vertical-align: middle;
      cursor: pointer;
      transition: color 0.3s;

      &:hover {
        color: #1890ff;
      }
    }

    .register {
      float: right;
    }
  }
  .ant-divider-horizontal.ant-divider-with-text-center {
    padding: 0 45px 0 35px;
    font-size: 12px !important;
    color: #717576 !important;
    font-weight: 400 !important;
  }
}

</style>
